<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<!--// lzf的我的地址功能实现-->
<template>
  <div class="my-address">
    <!-- 头部标题 -->

    <el-card shadow="hover" class="header-card">
      <div class="cart-header">
        <div class="header-left">
          <h1 class="cart-title">我的地址管理</h1>
        </div>
        <el-button type="primary"  @click="backToShopping" class="back-btn">
          返回主会场
        </el-button>
      </div>
    </el-card>
    <br>
    <!-- 地址列表 -->
    <div v-loading="loading" class="address-list">
      <div v-for="address in addresses" :key="address.id"
           :class="['address-card', { 'default-address': address.is_default }]">
        <div class="address-header">
          <span class="name">{{ address.name || '未提供姓名' }}</span>
          <span class="phone">{{ address.phone || '未提供电话' }}</span>
          <el-tag v-if="address.is_default" type="success" size="small">默认地址</el-tag>
        </div>

        <div class="address-content">
          {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detail }}
        </div>

        <div class="address-actions">
          <el-button size="small" plain @click="setDefault(address.id)" :disabled="address.is_default">
            {{ address.is_default ? '默认地址' : '设为默认' }}
          </el-button>
          <el-button size="small" plain @click="editAddress(address)">编辑</el-button>
          <el-button size="small" type="danger" plain @click="deleteAddress(address.id)">删除</el-button>
        </div>
      </div>

      <!-- 空状态提示 -->
      <div v-if="!loading && addresses.length === 0" class="empty-state">
        <el-icon class="empty-icon"><Location /></el-icon>
        <p>您还没有添加收货地址</p>
        <el-button type="primary" @click="handleAddAddress" size="small">添加新地址</el-button>
      </div>
    </div>

    <!-- 添加地址按钮 -->
    <div class="add-address">
      <el-button type="primary" :icon="Plus" @click="handleAddAddress">添加新地址</el-button>
    </div>

    <!-- 添加/编辑地址表单 -->
    <el-dialog
        :title="currentAddress.id ? '编辑地址' : '添加新地址'"
        v-model="showForm"
        width="500px"
        @closed="resetForm">
      <el-form :model="currentAddress" label-width="80px">
        <el-form-item label="收货人" required>
          <el-input v-model="currentAddress.name" placeholder="请输入姓名" clearable />
        </el-form-item>

        <el-form-item label="手机号" required>
          <el-input v-model="currentAddress.phone" placeholder="请输入手机号" clearable />
        </el-form-item>

        <el-form-item label="所在地区">
          <el-cascader
              v-model="currentAddress.region"
              :options="regionOptions"
              placeholder="请选择省/市/区"
              clearable
          />
        </el-form-item>


        <el-form-item label="详细地址">
          <el-input
              v-model="currentAddress.detail"
              type="textarea"
              placeholder="街道、小区、门牌号"
              :rows="3"
              clearable />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="currentAddress.is_default">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="saveAddress" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {ArrowLeft, Location} from '@element-plus/icons-vue'
import { useUserInfoStore } from '@/stores/userInfo'
import { addressApi } from '@/api/user'
import { regionData } from 'element-china-area-data' // 安装包见下方说明
import { Plus } from '@element-plus/icons-vue'
// 地区级联选项（省市区）
const regionOptions = regionData

// currentAddress 增加一个 region 字段来绑定级联值
//currentAddress.region = []

function getLabelsFromCodes(codes, options = regionOptions) {
  const labels = []
  let children = options
  for (const code of codes) {
    const found = children.find(item => item.value === code)
    if (!found) break
    labels.push(found.label)
    children = found.children || []
  }
  return labels
}
// 当保存地址前，将 region 拆分为省/市/区
const parseRegion = () => {
  if (Array.isArray(currentAddress.region)) {
    const [provinceCode, cityCode, districtCode] = currentAddress.region
    currentAddress.province = getLabelsFromCodes([provinceCode])[0] || ''
    currentAddress.city = getLabelsFromCodes([provinceCode, cityCode])[1] || ''
    currentAddress.district = getLabelsFromCodes([provinceCode, cityCode, districtCode])[2] || ''
  }
}



const router = useRouter()
const userStore = useUserInfoStore()

// 获取用户ID
const userId = computed(() => {
  return userStore?.userInfo?.id || null
})

// 检查登录状态
const isLoggedIn = computed(() => {
  return userStore?.userInfo && !!userStore.userInfo.id
})

const addresses = ref([])
const loading = ref(true)
const saving = ref(false)
const showForm = ref(false)
const currentAddress = reactive({
  id: null,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  is_default: false,
  region: [],
})

// 登录检查
const checkLogin = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  return true
}

// 获取地址列表 - 修复数据格式处理
const fetchAddresses = async () => {
  try {
    if (!checkLogin()) return

    loading.value = true
    const userID = userId.value

    if (!userID) {
      ElMessage.error('用户信息错误')
      return
    }

    const response = await addressApi.getUserAddresses(userID)

    if (response.code === 0 && Array.isArray(response.data)) {
      addresses.value = response.data.map(addr => {
        return {
          id: addr.id,
          name: addr.receiverName || userStore.userInfo?.username || '收货人',
          phone: addr.receiverPhone || userStore.userInfo?.mobile || '未提供手机号',
          province: addr.province || '',
          city: addr.city || '',
          district: addr.district || '',
          detail: addr.detail || '',
          is_default: addr.is_default ?? addr.isDefault ?? false,
          region: [], // 不再需要编码
        }
      })


      return // ✅ 成功后返回，避免进入错误处理逻辑
    } else {
      console.warn('响应格式错误:', response)
      ElMessage.error('获取地址列表失败: 数据格式异常')
      return
    }

  } catch (error) {
    console.error('获取地址列表失败:', error)

    let errorMessage = '获取地址列表失败: 未知错误'

    if (error.response) {
      if (error.response.status === 401) {
        errorMessage = '登录已过期，请重新登录'
        userStore.clearUserInfo()
        router.push('/login')
      } else if (error.response.data && error.response.data.message) {
        errorMessage = `获取地址列表失败: ${error.response.data.message}`
      } else {
        errorMessage = `服务异常 (${error.response.status})`
      }
    } else if (error.request) {
      errorMessage = '请求超时，请检查网络连接'
    } else {
      errorMessage = `请求错误: ${error.message}`
    }

    ElMessage.error(errorMessage)
    addresses.value = []
  } finally {
    loading.value = false
  }
}


// 返回主会场
const backToShopping = () => {
  router.push('/shopping')
}

// 设置默认地址
const setDefault = async (id) => {
  try {
    if (!checkLogin()) return

    const userID = userId.value
    if (!userID) {
      ElMessage.error('用户信息错误')
      return
    }

    // 调用设置默认地址接口
    await addressApi.setDefaultAddress(id, userID)
    ElMessage.success('设置默认地址成功')

    // 重新获取地址列表
    await fetchAddresses()
  } catch (error) {
    console.error('设置默认地址失败:', error)
    const errorMsg = error.response?.data?.message ||
        error.message ||
        '服务异常'
    ElMessage.error(`设置默认地址失败: ${errorMsg}`)
  }
}

// 处理添加地址
const handleAddAddress = () => {
  if (!checkLogin()) return
  resetForm()

  // 自动填充当前用户信息作为默认值
  const userInfo = userStore.userInfo
  if (userInfo) {
    currentAddress.name = userInfo.username || '' // 使用用户名
    currentAddress.phone = userInfo.mobile || '' // 使用手机号
  }
  showForm.value = true
}

// 编辑地址
const editAddress = (address) => {
  if (!checkLogin()) return

  // 复制地址数据
  Object.assign(currentAddress, {
    id: address.id,
    name: address.name || '',
    phone: address.phone || '',
    province: address.province || '',
    city: address.city || '',
    district: address.district || '',
    detail: address.detail || '',
    is_default: address.is_default || false,
    region: [address.provinceCode, address.cityCode, address.districtCode] // ✅ 使用编码而非名称
  })

  showForm.value = true
}

// 删除地址
const deleteAddress = async (id) => {
  try {
    if (!checkLogin()) return

    // 确认对话框
    await ElMessageBox.confirm('确定删除该地址吗？删除后将无法恢复', '提示', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 调用删除地址接口
    await addressApi.deleteAddress(id)
    ElMessage.success('地址已删除')

    // 重新获取地址列表
    await fetchAddresses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      const errorMsg = error.response?.data?.message ||
          error.message ||
          '服务异常'
      ElMessage.error(`删除地址失败: ${errorMsg}`)
    }
  }
}

// 保存地址 - 更新数据格式匹配
const saveAddress = async () => {
  try {
    if (!checkLogin()) return

    // 基础验证
    if (!currentAddress.name.trim() || !currentAddress.phone.trim()) {
      ElMessage.warning('请填写有效的收货人和手机号')
      return
    }

    saving.value = true
    const userID = userId.value

    if (!userID) {
      ElMessage.error('用户信息错误')
      return
    }

    parseRegion()
    // 准备提交数据 - 匹配后端字段命名
    const addressData = {
      id: currentAddress.id,
      userId: userStore.userInfo.id,
      receiverName: currentAddress.name,   // 注意：后端可能使用receiverName
      receiverPhone: currentAddress.phone, // 注意：后端可能使用receiverPhone
      province: currentAddress.province,
      city: currentAddress.city,
      district: currentAddress.district,
      detail: currentAddress.detail,
      // 注意：后端字段名为 "default"
      default: currentAddress.is_default
    }

    // 根据ID判断是新增还是更新
    if (currentAddress.id) {
      // 更新地址
      await addressApi.updateAddress(currentAddress.id, addressData)
      ElMessage.success('地址更新成功')
    } else {
      // 创建新地址
      const response = await addressApi.createAddress(addressData)
      ElMessage.success('地址添加成功')

      // 如果创建成功，保存新地址的ID
      if (response.data && response.data.id) {
        currentAddress.id = response.data.id
      }
    }

    // 如果设为默认地址，单独调用设置默认接口
    if (addressData.default && currentAddress.id) {
      await addressApi.setDefaultAddress(currentAddress.id, userID)
      ElMessage.success('默认地址已更新')
    }

    // 关闭表单
    showForm.value = false

    // 重新获取地址列表
    await fetchAddresses()
  } catch (error) {
    console.error('保存地址失败:', error)
    const errorMsg = error.response?.data?.message ||
        error.message ||
        '服务异常'
    ElMessage.error(`保存地址失败: ${errorMsg}`)
  } finally {
    saving.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(currentAddress, {
    id: null,
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    is_default: false,
    region:[],
  })
}

// 组件挂载时加载地址
onMounted(() => {
  if (isLoggedIn.value) {
    fetchAddresses()
  } else {
    ElMessage.warning('请先登录')
    router.push('/login')
  }
})

onMounted(() => {
  userStore.fetchUserInfo()
})

</script>

<style scoped>
/* 保持原有样式不变 */
.my-address {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.address-list {
  margin-bottom: 30px;
}

.address-card {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.address-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.address-card.default-address {
  border-left: 4px solid #409eff;
  background-color: #f0f8ff;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.address-header .name {
  font-weight: bold;
  font-size: 16px;
  margin-right: 15px;
}

.address-header .phone {
  color: #666;
  margin-right: 15px;
}

.address-content {
  color: #555;
  font-size: 14px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #f0f0f0;
}

.address-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.add-address {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 60px;
  color: #e0e0e0;
  margin-bottom: 20px;
}

.empty-state p {
  color: #999;
  margin-bottom: 20px;
}

.back-icon {
  font-size: 20px;
  margin-right: 10px;
  cursor: pointer;
  height: 40px;
  display: flex;
  align-items: center;
}

.header-card {
  position: relative;
  overflow: hidden; /* 避免图片超出 */
}

.header-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background-image: url('@/assets/IMG_20250630_185554.png'); /* 替换为你的图片路径 */
  background-size: cover;
  background-position: center;
  opacity: 1; /* 控制透明度，避免遮挡文字 */
  z-index: 0;
}

.cart-header {
  position: relative;
  z-index: 1; /* 确保内容在背景图上层 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.cart-title {
  font-size: 24px;
  font-weight: bold;
}

.back-icon {
  cursor: pointer;
  font-size: 20px;
  margin-right: 10px;
}

.back-btn {
  margin-left: 10px;
}
</style>